package service

import (
	"go-server/db"
	"go-server/models"
	"time"
)

type UserService struct {
}

var User UserService = UserService{}

func (UserService) Login(sysUserDto models.SysUser) (models.SysUser, error) {
	var sysUser models.SysUser
	err := db.DB.Where("username = ? and password = ?", sysUserDto.Username, sysUserDto.Password).First(&sysUser).Error
	return sysUser, err
}

func (UserService) List(sysUserListDto *models.SysUserListDto) ([]models.SysUser, error) {
	var sysUsers []models.SysUser
	var sysUserList models.SysUserListDto
	if sysUserListDto.Search != "" {
		sysUserList.Search = sysUserListDto.Search
	}
	err := db.DB.Where(&sysUserList).Find(&sysUsers).Error
	return sysUsers, err
}

func (UserService) Info(id int) (models.SysUser, error) {
	var sysUser models.SysUser
	err := db.DB.Where("user_id = ?", id).First(&sysUser).Error
	return sysUser, err
}

func (UserService) Save(dto *models.SysUser) bool {
	dto.CreateTime = time.Now()
	db.DB.NewRecord(&dto)
	err := db.DB.Save(&dto).Error
	if err != nil {
		return false
	}
	return true
}

func (UserService) Update(dto *models.SysUser) bool {
	err := db.DB.Model(&dto).Update(&dto).Error
	if err != nil {
		return false
	} else {
		return true
	}
}

func (UserService) Delete(id int) bool {
	sysUser := models.SysUser{UserId: id}
	err := db.DB.Delete(&sysUser).Error
	if err != nil {
		return false
	} else {
		return true
	}
}
